
import 'package:bot_toast/bot_toast.dart';
import 'package:common_utils/common_utils.dart';
import 'package:dio/dio.dart';
import 'package:exams_app/home_module/exams_module/aiface_page.dart';
import 'package:exams_app/net/DioManager.dart';
import 'package:exams_app/net/persisten_storage.dart';
import 'package:exams_app/widget/hexcolor.dart';


import 'package:flutter/material.dart';
import 'package:get/get.dart'as fromdata;
import 'package:get/get_core/src/get_main.dart';
import 'package:get/get_state_manager/src/simple/get_controllers.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';
import 'package:flutter_spinkit/flutter_spinkit.dart';

import 'package:exams_app/home_module/exams_module/shuaface_page.dart';

class RealNameAuthenLogic extends GetxController {



  var tf1 = TextEditingController();
  var tf2 = TextEditingController();
  var tf3 = TextEditingController();
  var tf4 = TextEditingController();



  var imagePath1 = ''.obs ;
  //
  var baseString1 ;
  //
  var imagePath2 = ''.obs;
  //
  var baseString2;



  /// 修改名称 身份证 号码 '
  void upDataWithNameAnCard(var name,var cardID,var cardHeader,var cardTails,bool is_confirm)async{

    BotToast.showLoading();

    var params = {

      'access_token': await PersistentStorage().getStorage('acctoken'),
      // 'uid': await PersistentStorage().getStorage('uid'),
      'uid': 2,
      // 'partner_id': await PersistentStorage().getStorage('partner_id'),
      'partner_id': 3,
      'model': 'res.partner',
      'form-field-char-full_name':name,
      'form-field-char-sfz':cardID,
      'form-field-char-sfz_heads':cardHeader,
      'form-field-char-sfz_tails':cardTails,
      'form-field-boolean-is_confirm':is_confirm,

      'form-field-char-exam_company_name':tf4.text,
      'form-field-char-exam_project_name':tf3.text,



      // 'fields': 'form-field-char-name,form-field-char-sfz,form-field-char-sfz_heads,form-field-char-sfz_tails,',
      // 'domain': "[('user_id', '=', ${await PersistentStorage().getStorage('uid')})]",  //#我的表达式
    };

    String result = await DioUtils(url: await PersistentStorage().getStorage('urlStr')).post('/api/v1/write/${await PersistentStorage().getStorage('partner_id')}',data:params);

    Map json = jsonDecode(result);

    if(json['errmsg'] == 'ok'){

      Get.to(ShuaFacePage());

    }

  }


   Future openCamera()async{

    var image = await ImagePicker.pickImage(source: ImageSource.camera,imageQuality: 100);

    return image;
  }

   Future openGallery()async{

    var image = await ImagePicker.pickImage(source: ImageSource.gallery,imageQuality: 100);

    return image;
  }

  void onClickUpCardHeader()async{
    showModalBottomSheet(
        backgroundColor:Colors.transparent,
        isScrollControlled:true,
        context: Get.overlayContext,
        builder: (BuildContext context){
          return StatefulBuilder(
              builder:(context1, state) {

                return Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  ),
                  child: Column(
                    children: [
                      TextButton(child: Text('拍照',style: TextStyle(color: Theme.of(context).primaryColor),),onPressed: ()async{
                        openCamera().then((value)async{

                          var imageys = await imageCompressAndGetFile(value);
                          List bytes = await imageys.readAsBytes();
                          String bs64 = base64Encode(bytes);
                          String bs64Image =bs64;
                          baseString1 = bs64Image;
                          getIDcarid(baseString1).then((respone) {
                            if(respone['idcard_number_type']==1){
                              imagePath1.value = value.path;
                            }
                          });

                        });
                        Get.back();
                      },),
                      Divider(color: Colors.grey[200],),
                      TextButton(child: Text('从相册选择',style: TextStyle(color: Theme.of(context).primaryColor),),onPressed: ()async{
                        openGallery().then((value)async{


                          var imageys = await imageCompressAndGetFile(value);

                          List bytes = await imageys.readAsBytes();


                          String bs64 = base64Encode(bytes);

                          String bs64Image =bs64;
                          baseString1 = bs64Image;
                          getIDcarid(baseString1).then((respone) {
                            if(respone['idcard_number_type']==1){
                              imagePath1.value = value.path;
                            }
                          });

                        });

                        Get.back();
                      },),
                      Divider(color: Colors.grey[200],thickness: 10,height: 30,),
                      TextButton(child: Text('取消',style: TextStyle(color: HexColor('#515151')),),onPressed: ()=>Get.back(),),
                    ],
                  ),
                  height: 200,
                );

              }

          );

        }

    );
  }

  void onClickUpCardFoot()async{
    showModalBottomSheet(
        backgroundColor:Colors.transparent,
        isScrollControlled:true,
        context: Get.overlayContext,
        builder: (BuildContext context){
          return StatefulBuilder(
              builder:(context1, state) {
                return Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius: BorderRadius.all(Radius.circular(10.0)),
                  ),
                  child: Column(
                    children: [
                      TextButton(child: Text('拍照',style: TextStyle(color: Theme.of(context).primaryColor),),onPressed: ()async{
                        openCamera().then((value)async{

                          var imageys = await imageCompressAndGetFile(value);

                          List bytes = await imageys.readAsBytes();

                          String bs64 = base64Encode(bytes);

                          String bs64Image =bs64;
                          baseString2 = bs64Image;
                          getIDcaridback(baseString2).then((respone){
                            if(respone['image_status']=='normal'){
                              imagePath2.value = value.path;
                            }
                          });



                        });
                        Get.back();
                      },),
                      Divider(color: Colors.grey[200],),
                      TextButton(child: Text('从相册选择',style: TextStyle(color: Theme.of(context).primaryColor)),onPressed: ()async{
                        openGallery().then((value)async{


                          var imageys = await imageCompressAndGetFile(value);


                          List bytes = await imageys.readAsBytes();

                          String bs64 = base64Encode(bytes);

                          String bs64Image =bs64;

                          baseString2 = bs64Image;

                          getIDcaridback(baseString2).then((respone){
                            if(respone['image_status']=='normal'){
                              imagePath2.value = value.path;
                            }
                          });


                        });

                        Get.back();
                      },),
                      Divider(color: Colors.grey[200],thickness: 10,height: 30,),
                      TextButton(child: Text('取消',style: TextStyle(color: HexColor('#515151')),),onPressed: ()=>Get.back(),),
                    ],
                  ),
                  height: 200,
                );
              }
          );
        }
    );
  }

  Future getIDcarid(var front)async{

    // BotToast.showLoading(clickClose: true);

    Get.dialog(WorkSpace());

    String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${await getToken()}";

    // String imgParam = json.encode(front);


    // var params = {
    //
    //   'image':front,
    //   'id_card_side':'front',
    // };
    //

    var formData = FormData.fromMap({

      "image": front,
      'id_card_side':'front',
    });

    var response =await  Dio().post(url,data:formData);

    /**
     *
     * - 1： 身份证正面所有字段全为空
        0： 身份证证号不合法，此情况下不返回身份证证号
        1： 身份证证号和性别、出生信息一致
        2： 身份证证号和性别、出生信息都不一致
        3： 身份证证号和出生信息不一致
        4： 身份证证号和性别信息不一致
     */
    if(Get.isDialogOpen){
      Get.back();
    }
    // tf1.text = response.data['姓名']['words'];

    // if(response.data['姓名']['words']){
    // }

    if(response.data['image_status']!='normal'){
      // BotToast.showText(text: '请上传正确的身份证信息');
      BotToast.showText(text: '请上传身份证正面照');
      return;
    }

    if(response.data['idcard_number_type']==-1){
      BotToast.showText(text: '请上传正确的身份证信息');
      return;
    }
    if(response.data['idcard_number_type']==0){
      BotToast.showText(text: '身份证证号不合法');
      return;
    }
    if(response.data['idcard_number_type']==2){
      BotToast.showText(text: '身份证证号和性别、出生信息都不一致');
      return;
    }
    if(response.data['idcard_number_type']==3){
      BotToast.showText(text: '身份证证号和出生信息不一致');
      return;
    }
    if(response.data['idcard_number_type']==4){
      BotToast.showText(text: '身份证证号和性别信息不一致');
      return;
    }
    if(response.data['idcard_number_type']==1){
      // upDataWithNameAnCard('${tf1.text}', '${tf2.text}', baseString1, baseString2,true);
      tf1.text = response.data['words_result']['姓名']['words'];
      tf2.text = response.data['words_result']['公民身份号码']['words'];
    }

    print(response.data);
    update();
    return response.data;
  }

  /// 身份证反面
  ///
  Future getIDcaridback(var back)async{

    // BotToast.showLoading(clickClose: true);

    Get.dialog(WorkSpace());

    String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/idcard?access_token=${await getToken()}";

    // String imgParam = json.encode(front);


    // var params = {
    //
    //   'image':front,
    //   'id_card_side':'front',
    // };
    //

    var formData = FormData.fromMap({

      "image": back,
      'id_card_side':'back',
    });

    var response =await  Dio().post(url,data:formData);
    if(Get.isDialogOpen){
      Get.back();
    }

    if(response.data['image_status']!='normal'){
      BotToast.showText(text: '请上传身份证反面照片');
      return;
    }
    // if(response.data['idcard_number_type']==0){
    //   BotToast.showText(text: '身份证证号不合法');
    //   return;
    // }
    // if(response.data['idcard_number_type']==2){
    //   BotToast.showText(text: '身份证证号和性别、出生信息都不一致');
    //   return;
    // }
    // if(response.data['idcard_number_type']==3){
    //   BotToast.showText(text: '身份证证号和出生信息不一致');
    //   return;
    // }
    // if(response.data['idcard_number_type']==4){
    //   BotToast.showText(text: '身份证证号和性别信息不一致');
    //   return;
    // }
    // if(response.data['idcard_number_type']==1){
    //   // upDataWithNameAnCard('${tf1.text}', '${tf2.text}', baseString1, baseString2,true);
    //   tf1.text = response.data['words_result']['姓名']['words'];
    //   tf2.text = response.data['words_result']['公民身份号码']['words'];
    // }
    print(response.data);
    update();
    return response.data;
  }


  getToken()async{
    // 官网获取的 API Key 更新为你注册的
    String clientId = "HuqpI8yaQpEGM9PkDdt48aia";
    // 官网获取的 Secret Key 更新为你注册的
    String clientSecret = "8kA82Fz2aehqfVcNrlVNfTbguokvxz1a";
    // 获取token地址
    String authHost = "https://aip.baidubce.com/oauth/2.0/token?";

    var params = {
      'grant_type':'client_credentials',
      'client_id':clientId,
      'client_secret':clientSecret,
    };

    var response = await Dio().post(authHost,queryParameters: params);



    print('${response.data['access_token']}');


    return response.data['access_token'];

    // var result = await DioUtils(url: authHost).post('',data:params);
  }



  void onClickNextMthod()async{


    if(tf1.text.isEmpty){
      BotToast.showText(text: '请输入姓名');
      return;
    }
    if(tf2.text.isEmpty){
      BotToast.showText(text: '请输入正确的身份证号码');
      return;
    }
    if(!RegexUtil.isIDCard(tf2.text)){
      BotToast.showText(text: '请输入正确的身份证号码');
      return;
    }
    if(tf3.text.isEmpty){
      BotToast.showText(text: '请输入项目名称');
      return;
    }
    if(tf4.text.isEmpty){
      BotToast.showText(text: '请输入公司名称');
      return;
    }



    if(baseString1 == null){
      BotToast.showText(text: '请上传身份证照片');
      return;
    }
    if(baseString2==null){
      BotToast.showText(text: '请上传身份证照片');
      return;
    }


    upDataWithNameAnCard('${tf1.text}', '${tf2.text}', baseString1, baseString2,true);


    // getIDcarid(baseString1);


  }

}
